<template>
  <Dialog v-model:open="open">
    <DialogContent class="max-w-md">
      <DialogHeader>AI文案生成</DialogHeader>
      <div class="mb-2">
        <label class="block text-sm mb-1">文案风格：</label>
        <div class="flex gap-2">
          <Button
            v-for="style in styles"
            :key="style"
            :variant="style === selectedStyle ? 'default' : 'outline'"
            size="sm"
            @click="selectStyle(style)"
            >{{ style }}</Button
          >
        </div>
      </div>
      <div class="mb-2">
        <label class="block text-sm mb-1">短文案：</label>
        <Input v-model="shortCaption" readonly />
        <Button
          size="sm"
          variant="ghost"
          class="ml-2"
          @click="copy(shortCaption)"
          >复制</Button
        >
        <Button size="sm" variant="ghost" @click="regenerate">重新生成</Button>
        <Button size="sm" variant="ghost" @click="toggleFavorite('short')">{{
          shortFavorite ? "取消收藏" : "收藏"
        }}</Button>
      </div>
      <div class="mb-2">
        <label class="block text-sm mb-1">长话术：</label>
        <Input v-model="longCaption" readonly />
        <Button
          size="sm"
          variant="ghost"
          class="ml-2"
          @click="copy(longCaption)"
          >复制</Button
        >
        <Button size="sm" variant="ghost" @click="regenerate">重新生成</Button>
        <Button size="sm" variant="ghost" @click="toggleFavorite('long')">{{
          longFavorite ? "取消收藏" : "收藏"
        }}</Button>
      </div>
      <DialogFooter>
        <Button @click="open = false">关闭</Button>
      </DialogFooter>
    </DialogContent>
  </Dialog>
</template>

<script setup lang="ts">
import { ref, watch } from "vue";
import { Dialog, DialogContent, DialogHeader, DialogFooter } from "./ui/dialog";
import { Button } from "./ui/button";
import { Input } from "./ui/input";

const props = defineProps<{ open: boolean; image: any }>();
const emit = defineEmits(["update:open", "favorite"]);

const styles = ["促销型", "温情型", "专业型"];
const selectedStyle = ref(styles[0]);
const open = ref(props.open);
const shortCaption = ref("");
const longCaption = ref("");
const shortFavorite = ref(false);
const longFavorite = ref(false);

watch(
  () => props.open,
  v => (open.value = v)
);
watch(open, v => emit("update:open", v));

watch(
  [selectedStyle, () => props.image],
  () => {
    generate();
  },
  { immediate: true }
);

function selectStyle(style: string) {
  selectedStyle.value = style;
}

function generate() {
  // 这里应调用AI接口，现用模拟文案
  shortCaption.value = `[${selectedStyle.value}] ${
    props.image?.name || ""
  } 的短文案`;
  longCaption.value = `[${selectedStyle.value}] ${
    props.image?.name || ""
  } 的长话术`;
}

function regenerate() {
  generate();
}

function copy(text: string) {
  // 优先使用现代 Clipboard API
  if (navigator.clipboard && navigator.clipboard.writeText) {
    navigator.clipboard
      .writeText(text)
      .then(() => {
        console.log("文案已复制到剪贴板");
      })
      .catch(err => {
        console.warn("Clipboard API 失败，使用降级方案:", err);
        fallbackCopyToClipboard(text);
      });
  } else {
    // 降级方案：使用传统的 document.execCommand
    fallbackCopyToClipboard(text);
  }
}

// 降级复制方案
function fallbackCopyToClipboard(text: string) {
  try {
    // 创建临时文本区域
    const textArea = document.createElement("textarea");
    textArea.value = text;
    textArea.style.position = "fixed";
    textArea.style.left = "-999999px";
    textArea.style.top = "-999999px";
    document.body.appendChild(textArea);

    // 选择文本并复制
    textArea.focus();
    textArea.select();
    const successful = document.execCommand("copy");

    // 清理临时元素
    document.body.removeChild(textArea);

    if (successful) {
      console.log("文案已复制到剪贴板");
    } else {
      console.error("复制失败");
    }
  } catch (err) {
    console.error("复制失败:", err);
  }
}

function toggleFavorite(type: "short" | "long") {
  if (type === "short") shortFavorite.value = !shortFavorite.value;
  else longFavorite.value = !longFavorite.value;
  emit("favorite", {
    type,
    value: type === "short" ? shortFavorite.value : longFavorite.value,
  });
}
</script>
